// WebUI v2.5.0-beta.4
// https://webui.me
// https://github.com/webui-dev/webui
// Copyright (c) 2020-2025 Hassan Draga.
// Licensed under MIT License.
// All rights reserved.
// Canada.

async function jsToCHeader(inputFilename, outputFilename) {
    try {
        console.log(`Converting '${inputFilename}' to '${outputFilename}'...`);
        // Comment block
        const comment = `// WebUI v2.5.0-beta.4\n// https://webui.me\n// https://github.com/webui-dev/webui\n// Copyright (c) 2020-2025 Hassan Draga.\n// Licensed under MIT License.\n// All rights reserved.\n// Canada.\n\n`;
        // Read JS file content
        const fs = require('fs').promises;
        let content = await fs.readFile(inputFilename, 'utf-8');
        // Add comment to js
        let newContent = comment + content;
        await fs.writeFile(inputFilename, newContent);
        // Convert each character in JS content to its hexadecimal value
        const hexValues = [...newContent].map(char => `0x${char.charCodeAt(0).toString(16).padStart(2, '0')}`);
        // Prepare the content for the C header file
        let headerContent = `${comment}// --- PLEASE DO NOT EDIT THIS FILE -------\n// --- THIS FILE IS GENERATED BY JS2C.JS --\n\n`;
        headerContent += `#ifndef WEBUI_BRIDGE_H\n#define WEBUI_BRIDGE_H\n`;
        headerContent += `unsigned char webui_javascript_bridge[] = { `;
        // Split the hexadecimal values to make the output more readable, adding a new line every 10 values
        for (let i = 0; i < hexValues.length; i += 10) {
            headerContent += "\n    " + hexValues.slice(i, i + 10).join(', ') + ',';
        }
        headerContent += `\n    0x00\n};\n\n#endif // WEBUI_BRIDGE_H`;
        // Write the header content to the output file
        await fs.writeFile(outputFilename, headerContent);
    } catch (error) {
        if (error.code === 'ENOENT') {
            console.error(`Error: File '${inputFilename}' not found.`);
        } else {
            console.error('An error occurred:', error);
        }
    }
}

// Main
jsToCHeader('webui.js', 'webui_bridge.h');
